package com.aqie.rabbit.access;

import com.alibaba.fastjson.JSON;
import com.aqie.rabbit.bean.api.base.CodeMsg;
import com.aqie.rabbit.bean.api.base.ResponseModel;
import com.aqie.rabbit.bean.db.User;
import com.aqie.rabbit.redis.AccessKey;
import com.aqie.rabbit.redis.IRedisService;
import com.aqie.rabbit.service.IUserService;
import com.aqie.rabbit.service.Impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * 登录拦截器
 */
@Service
public class AccessInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    IUserService userService;

    @Autowired
    IRedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        if (handler instanceof HandlerMethod){
            User user = getUser(request, response);

            UserContext.setUser(user);

            HandlerMethod handlerMethod = (HandlerMethod) handler;
            AccessLimit accessLimit = handlerMethod.getMethodAnnotation(AccessLimit.class);
            if (accessLimit == null){
                return true;
            }
            int seconds = accessLimit.seconds();
            int maxCount = accessLimit.maxCount();
            boolean needLogin = accessLimit.needLogin();
            String key = request.getRequestURI();
            if (needLogin){
                if (user == null){
                    render(response,CodeMsg.TOKEN_INVALID_ERROR);
                    return false;
                }
                key += "_" + user.getId();
            }
            // redis计数 进行接口限流
            AccessKey accessKey = AccessKey.withExpire(seconds);
            Integer count = redisService.get(accessKey, key, Integer.class);
            if (count == null){
                redisService.set(accessKey, key, 1);
            }else if (count < maxCount){
                redisService.incr(accessKey, key);
            }else {
                render(response,CodeMsg.ACCESS_LIMIT_REACHED);
                return false;
            }
        }
        return true;
    }

    private void render(HttpServletResponse response, CodeMsg codeMsg)throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        String str  = JSON.toJSONString(ResponseModel.error(codeMsg));
        out.write(str.getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }

    private User getUser(HttpServletRequest request, HttpServletResponse response){
        String paramToken = request.getHeader(UserServiceImpl.COOKIE_NAME_TOKEN);

        if(StringUtils.isEmpty(paramToken)) {
            return null;
        }
        return userService.findByToken(paramToken);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
        UserContext.removeUser();
    }
}
